<?php
declare(strict_types=1);

namespace TairClient\Client;

use TairClient\TairException;
use Hyperf\Redis\Redis;
use Hyperfx\Framework\Logger\Logx;

class TairBase {

    protected function checkArgument(array $params, string $arg) {
        if (!array_key_exists($arg, $params)) {
            $msg = sprintf('param %s not exits', $arg);
            Logx::get()->error($msg, [
                'params' => $params,
                'arg' => $arg,
            ]);
            throw new TairException(sprintf('param %s not exits', $arg), 400);
        }
        return $params[$arg];
    }

    protected function checkNotEmpty($val) {
//        if (
//            (is_string($val) && strlen($val) == 0)
//            ||
//            (is_array($val) && empty($val))
//        ) {
        if (empty($val)) {
            $msg = sprintf('param %s not empty', $val);
            Logx::get()->error($msg, [
                'val' => $val,
            ]);
            throw new TairException(sprintf('param %s not empty', $val), 400);
        }
    }

    protected function then(callable $function, array $args = [], callable $errorCallback = null, bool $falseIsError = true){
        try {
            $result = $function(...$args);
        } catch (\Exception $e) {
            $errorCallback = !is_null($errorCallback) ? $errorCallback(...$args) : '';
            Logx::get()->alert($e->getMessage(), [
                'args' => $args,
                'error' => $errorCallback,
                'trace' => $e->getTraceAsString(),
            ]);
            throw new TairException($e->getMessage(), 500);
        }
        if ($falseIsError && false === $result) {
            $errorCallback = !is_null($errorCallback) ? $errorCallback(...$args) : '';
            $errorMsg = $this->client?->getLastError() ?: 'command run error';
            Logx::get()->alert($errorMsg, [
                'args' => $args,
                'error' => $errorCallback,
            ]);
            throw new TairException($errorMsg, 500);
        }
        return $result;
    }
}